#coding=utf-8

import time, urllib
from BeautifulSoup import BeautifulSoup 

import utils

def get_soup(code, year, quarter):
   
    url = 'http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/%s.phtml?year=%s&jidu=%s'%(code, year, quarter)
    s = utils.get_soup(url)
    return s

def get_data(soup) :

    def get_s(item):
        while True:
            r = item.string
            if r: return r.strip()
            item = item.contents[0]
            
    def get_data_from_row(row):

        r = []
        tds = row.findAll('td')

        for td in tds:
            r.append(get_s(td))

        if not r[0] :
            td0 = tds[0]
            rq = td0.contents[0].contents[1].string.strip()
            r[0] = rq

        return r

    r = []
    
    t = unicode('日期', 'u8')
    table = soup.find(text = t).parent.parent.parent.parent.parent
    trs = table.findAll('tr')[2:]

    for tr in trs:
        d = get_data_from_row(tr)
        r.append(d)

    r.reverse()
    
    return r

def get_histprice_by_quarter(code, year, quarter):

    s = get_soup(code, year, quarter)
    data = get_data(s)
    
    return data
